package com.cskaoyan;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.imageio.stream.FileImageInputStream;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 创建日期: 2022/05/18 10:59
 *
 * @author ciggar
 */
public class DruidDemo {


    static DataSource dataSource;

    static {

        try {
            Properties properties = new Properties();
//            FileInputStream fileInputStream = new FileInputStream("src/main/resources/druid.properties");
//            properties.load(fileInputStream);


            ClassLoader classLoader = DruidDemo.class.getClassLoader();

//            URL url = classLoader.getResource("druid.properties");
//            String path = url.getPath();
//            FileInputStream fileInputStream = new FileInputStream(path);
//            properties.load(fileInputStream);

            //file:/E:/cskaoyan/40workspace/code/maven-datasource/target/classes/druid.properties
            // path  /E:/cskaoyan/40workspace/code/maven-datasource/target/classes/druid.properties

//            System.out.println(url);
//            System.out.println("path:" + path);

            InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties");
            properties.load(resourceAsStream);


            dataSource = DruidDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static void main(String[] args) throws SQLException {

        // 获取连接
        Connection connection = dataSource.getConnection();

        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery("select * from account");

        while (resultSet.next()) {

            String name = resultSet.getString("name");
            int id = resultSet.getInt("id");

            System.out.println("id:" + id + ", name：" + name);

        }

        resultSet.close();
        statement.close();
        connection.close();

    }

}
